<?php

App::uses('Component', 'Controller');

class ApiComponent extends Component {

    private $base_url = null;
    private $base_params = array();
    
    
    public function initialize(Controller $controller) {
        parent::initialize($controller);
        
        $this->base_url = Configure::read('api_url');
    }
    
    public function getBaseParams() {
        return $this->base_params;
    }

    public function setBaseParams($base_params) {
        $this->base_params = $base_params;
    }
        
    public function setBaseURL($url) {
        $this->base_url = $url;
    }
    
    public function getBaseURL() {
        return $this->base_url != null ? $this->base_url : Configure::read('api_url');
    }
    
    public function post($url, $params = array()) {
        $base_url = $this->getBaseURL();
        
        if( stristr($base_url, $url) == false ) {
            $url = $base_url . $url;
        }
        
        return $this->request($url, $params, 'POST', 'json');
    }
    
    public function get($url, $params = array()) {
        $base_url = $this->getBaseURL();
        
        if( stristr($base_url, $url) == false ) {
            $url = $base_url . $url;
        }
        
        return $this->request($url, $params);
    }
    
    public function request($url, $params = null, $verb = 'GET', $format = 'json') {
        $cparams = array(
            'http' => array(
                'method' => $verb,
                'ignore_errors' => true,
                'header' => array("Content-Type: application/x-www-form-urlencoded", "Connection: close")
            )
        );
        if( $params !== null ) {
            
            // always include the APP_ID and APP_KEY 
            if(is_array($params) ) {
                $params['APP_ID'] = Configure::read('app_id');
                $params['APP_KEY'] = Configure::read('app_key');
                $params['HTTP_USER_AGENT'] = $_SERVER['HTTP_USER_AGENT'];
                $params['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR'];
                
                // remove all null values from the array
                $params = array_filter($params, function($var) {
                    return !is_null($var);
                });
            }
            
            $params = http_build_query($params);
            
            if( $verb == 'POST' ) {
                $cparams['http']['content'] = $params;
            } else {
                $url .= '?' . $params;
            }
            
            $cparams['http']['header'][] = "Content-Length: ". strlen($params);
        }

        $context = stream_context_create($cparams);
        $fp = @fopen($url, 'rb', false, $context);
        if( !$fp ) {
            $res = false;
        } else {
            // If you're trying to troubleshoot problems, try uncommenting the
            // next two lines; it will show you the HTTP response headers across
            // all the redirects:
            // $meta = stream_get_meta_data($fp);
            // var_dump($meta['wrapper_data']);
            $res = stream_get_contents($fp);
        }

        if( $res === false ) {
            throw new Exception("$verb $url failed:");
        }

        switch( $format ) {
            case 'json':
                $r = json_decode($res, true);
                if( $r === null ) {
                    throw new Exception("failed to decode $res as json");
                }
                return $r;

            case 'xml':
                $r = simplexml_load_string($res);
                if( $r === null ) {
                    throw new Exception("failed to decode $res as xml");
                }
                return $r;
        }
        return $res;
    }

}
?>
